<template>
  <div class="bg-white rounded-2xl shadow-sm p-8">
          <div class="bg-white rounded-2xl shadow-sm p-8">
            <div class="mb-8">
              <h1 class="text-2xl font-bold text-gray-900 mb-2">账户安全</h1>
              <p class="text-gray-500">保护您的账户安全，防止信息泄露</p>
            </div>

            <div class="mb-8 pb-8 border-b border-gray-200">
              <div class="flex items-center justify-between mb-4">
                <h2 class="text-lg font-semibold text-gray-900">账户安全等级</h2>
                <span :class="securityLevelClass" class="font-medium">{{ securityLevelText }}</span>
              </div>
              <div class="mb-3">
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div 
                    :class="securityProgressBarClass" 
                    class="h-2 rounded-full transition-all duration-300" 
                    :style="`width: ${securityScore}%`"
                  ></div>
                </div>
              </div>
              <p class="text-sm text-gray-500">{{ securityLevelDescription }}</p>
            </div>

            <div class="mb-8 pb-8 border-b border-gray-200">
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <h2 class="text-lg font-semibold text-gray-900 mb-2">修改密码</h2>
                  <p class="text-sm text-gray-500 mb-4">通过手机短信验证码重置密码，无需输入当前密码</p>
                  <div class="flex items-center gap-2" v-if="!showPasswordForm">
                    <div class="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center">
                      <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                    </div>
                    <span class="text-green-600 text-sm">已设置密码</span>
                  </div>
                </div>
                <button 
                  v-if="!showPasswordForm"
                  @click="showPasswordForm = true"
                  class="px-6 py-2 border border-blue-600 text-blue-600 rounded-lg hover:bg-blue-50 transition-colors"
                >
                  修改
                </button>
              </div>

              <!-- 修改密码表单：绑定手机号 + 短信验证码 + 新密码 -->
              <div v-if="showPasswordForm" class="mt-6 p-6 bg-gray-50 rounded-lg border border-gray-200">
                <div class="space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">绑定手机号</label>
                    <div class="flex items-center gap-3">
                      <div class="flex-1 px-4 py-3 border border-gray-200 rounded-lg bg-gray-100 text-gray-700">
                        {{ maskedPhone }}
                      </div>
                    </div>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">短信验证码</label>
                    <div class="flex gap-3">
                      <input 
                        type="text" 
                        v-model="passwordForm.smsCode"
                        placeholder="请输入短信验证码"
                        class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
                      />
                      <button
                        type="button"
                        @click="smsCountdown > 0 ? null : sendSmsCode()"
                        :disabled="smsCountdown > 0 || !userPhone"
                        class="px-4 py-3 border border-blue-600 text-blue-600 rounded-lg hover:bg-blue-50 transition-colors disabled:bg-gray-100 disabled:text-gray-400 whitespace-nowrap"
                      >
                        {{ smsCountdown > 0 ? `${smsCountdown}s 后重发` : '获取验证码' }}
                      </button>
                    </div>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">新密码</label>
                    <input 
                      type="password" 
                      v-model="passwordForm.newPassword"
                      @input="updatePasswordStrength"
                      placeholder="请输入新密码（至少6位）"
                      class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
                      :class="{'border-red-300': passwordForm.newPassword && passwordStrength.score < 3, 'border-yellow-300': passwordForm.newPassword && passwordStrength.score === 3, 'border-green-300': passwordForm.newPassword && passwordStrength.score >= 4}"
                    />
                    <!-- 密码强度指示器 -->
                    <div v-if="passwordForm.newPassword" class="mt-2">
                      <div class="flex items-center gap-2 mb-1">
                        <span class="text-xs font-medium" :class="passwordStrengthClass">{{ passwordStrengthText }}</span>
                        <div class="flex-1 flex gap-1">
                          <div 
                            v-for="i in 5" 
                            :key="i"
                            :class="[
                              i <= passwordStrength.score ? passwordStrengthBarClass : 'bg-gray-200',
                              'h-1 flex-1 rounded'
                            ]"
                          ></div>
                        </div>
                      </div>
                      <ul class="text-xs text-gray-500 mt-2 space-y-1">
                        <li v-for="tip in passwordStrength.tips" :key="tip" class="flex items-center gap-1">
                          <span :class="tip.passed ? 'text-green-600' : 'text-gray-400'">{{ tip.passed ? '✓' : '○' }}</span>
                          <span :class="tip.passed ? 'text-green-600' : 'text-gray-500'">{{ tip.text }}</span>
                        </li>
                      </ul>
                    </div>
                    <p v-else class="text-xs text-gray-500 mt-1">密码长度至少6位，建议包含大小写字母、数字和特殊字符</p>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">确认新密码</label>
                    <input 
                      type="password" 
                      v-model="passwordForm.confirmPassword"
                      placeholder="请再次输入新密码"
                      class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
                      :class="{'border-red-300': passwordForm.confirmPassword && passwordForm.newPassword !== passwordForm.confirmPassword}"
                    />
                    <p v-if="passwordForm.confirmPassword && passwordForm.newPassword !== passwordForm.confirmPassword" class="text-xs text-red-500 mt-1">两次输入的密码不一致</p>
                  </div>
                  <div class="flex items-center gap-3 pt-2">
                    <button 
                      @click="handleChangePassword"
                      :disabled="!canSubmitPasswordForm || isChangingPassword"
                      class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2"
                    >
                      <svg v-if="isChangingPassword" class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      <span>{{ isChangingPassword ? '修改中...' : '确认修改' }}</span>
                    </button>
                    <button 
                      @click="cancelPasswordForm"
                      class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      取消
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <div class="mb-8 pb-8 border-b border-gray-200">
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <h2 class="text-lg font-semibold text-gray-900 mb-2">手机验证</h2>
                  <p class="text-sm text-gray-500 mb-4">绑定手机可用于登录和找回密码</p>
                  <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center">
                      <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/></svg>
                    </div>
                    <span class="text-gray-700">{{ maskedPhone }}</span>
                  </div>
                </div>
                <div class="flex items-center gap-3">
                  <div class="flex items-center gap-2 text-green-600"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg><span class="text-sm">已验证</span></div>
                  <button class="text-blue-600 hover:text-blue-700 text-sm">更换</button>
                </div>
              </div>
            </div>

            <div class="mb-8 pb-8 border-b border-gray-200">
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <h2 class="text-lg font-semibold text-gray-900 mb-2">邮箱验证</h2>
                  <p class="text-sm text-gray-500 mb-4">绑定邮箱可用于登录和接收通知</p>
                  <div class="flex items-center gap-3" v-if="userEmail">
                    <div class="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center">
                      <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                    </div>
                    <span class="text-gray-700">{{ maskedEmail }}</span>
                  </div>
                  <div v-else class="text-gray-500 text-sm">未绑定邮箱</div>
                </div>
                <div class="flex items-center gap-3">
                  <div v-if="isEmailVerified" class="flex items-center gap-2 text-green-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                    <span class="text-sm">已验证</span>
                  </div>
                  <button 
                    v-if="!showEmailForm"
                    @click="openEmailForm"
                    class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    {{ emailButtonText }}
                  </button>
                </div>
              </div>

              <!-- 邮箱绑定/验证表单 -->
              <div v-if="showEmailForm" class="mt-6 p-6 bg-gray-50 rounded-lg border border-gray-200">
                <div class="space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">邮箱地址</label>
                    <input 
                      type="email" 
                      v-model="emailForm.email"
                      placeholder="请输入邮箱地址"
                      class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
                    />
                  </div>
                  <div v-if="emailForm.emailSent">
                    <label class="block text-sm font-medium text-gray-700 mb-2">验证码</label>
                    <div class="flex gap-3">
                      <input 
                        type="text" 
                        v-model="emailForm.verificationCode"
                        placeholder="请输入验证码"
                        class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
                      />
                      <button 
                        @click="resendEmailCode"
                        :disabled="emailCountdown > 0"
                        class="px-4 py-3 border border-blue-600 text-blue-600 rounded-lg hover:bg-blue-50 transition-colors disabled:bg-gray-100 disabled:text-gray-400 whitespace-nowrap"
                      >
                        {{ emailCountdown > 0 ? `${emailCountdown}s 后重发` : '重新发送' }}
                      </button>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">验证码已发送到您的邮箱（开发环境请查看后端日志）</p>
                  </div>
                  <div class="flex items-center gap-3 pt-2">
                    <button 
                      v-if="!emailForm.emailSent"
                      @click="sendEmailVerification"
                      :disabled="!isValidEmail || isSendingEmail"
                      class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2"
                    >
                      <svg v-if="isSendingEmail" class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      <span>{{ isSendingEmail ? '发送中...' : '发送验证码' }}</span>
                    </button>
                    <button 
                      v-else
                      @click="verifyEmail"
                      :disabled="!emailForm.verificationCode || isVerifyingEmail"
                      class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2"
                    >
                      <svg v-if="isVerifyingEmail" class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      <span>{{ isVerifyingEmail ? '验证中...' : '确认验证' }}</span>
                    </button>
                    <button 
                      @click="cancelEmailForm"
                      class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      取消
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <div>
              <h2 class="text-lg font-semibold text-gray-900 mb-6">最近登录记录</h2>
              <div v-if="loginHistory.length === 0" class="text-center py-8 text-gray-500">
                <p>暂无登录记录</p>
              </div>
              <div v-else class="space-y-4">
                <div 
                  v-for="(record, index) in loginHistory" 
                  :key="index"
                  class="flex items-center justify-between py-4"
                >
                  <div class="flex items-center gap-4">
                    <div class="w-12 h-12 bg-blue-50 rounded-full flex items-center justify-center">
                      <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                      </svg>
                    </div>
                    <div>
                      <div class="font-medium text-gray-900">{{ record.device }}</div>
                      <div class="text-sm text-gray-500">IP: {{ record.location }}</div>
                    </div>
                  </div>
                  <div class="flex items-center gap-3">
                    <span class="text-sm text-gray-500">{{ formatTime(record.time) }}</span>
                    <span v-if="record.isCurrent" class="px-3 py-1 bg-blue-50 text-blue-600 text-sm rounded-full">当前</span>
                </div>
                </div>
              </div>
            </div>
          </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'OrderSecurity',
  data() {
    return {
      showPasswordForm: false,
      isChangingPassword: false,
      passwordForm: {
        smsCode: '',
        newPassword: '',
        confirmPassword: ''
      },
      showEmailForm: false,
      isSendingEmail: false,
      isVerifyingEmail: false,
      emailCountdown: 0,
      emailTimer: null,
      userEmail: '',
      isEmailVerified: false,
      emailForm: {
        email: '',
        verificationCode: '',
        emailSent: false
      },
      loginHistory: [],
      passwordStrength: {
        score: 0,
        level: 'weak', // weak, fair, good, strong, very-strong
        tips: []
      },
      hasPassword: false, // 用户是否已设置密码
      currentPasswordStrength: 0, // 当前密码强度（如果用户已设置密码）
      isPhoneVerified: false, // 手机是否已验证
      userPhone: '', // 用户手机号
      smsCountdown: 0,
      smsTimer: null
    }
  },
  computed: {
    // 计算账户安全等级
    securityScore() {
      let score = 0
      const maxScore = 100

      // 密码强度 (0-40分)
      // 根据密码强度评分：0-1分(弱)=8分, 2分(一般)=16分, 3分(良好)=24分, 4分(强)=32分, 5分(非常强)=40分
      if (this.hasPassword) {
        const strengthScore = Math.min(this.currentPasswordStrength * 8, 40)
        score += strengthScore
      }

      // 手机验证 (0-20分)
      if (this.isPhoneVerified) {
        score += 20
      } else {
        // 如果已绑定手机但未验证，给10分
        // 由于用户已登录，通常手机已验证，这里给15分作为默认值
        score += 15
      }

      // 邮箱验证 (0-20分)
      if (this.isEmailVerified) {
        score += 20
      } else {
        // 如果已绑定但未验证，给10分
        if (this.userEmail) {
          score += 10
        }
      }

      // 其他安全措施 (0-20分)
      // 密码长度、复杂度等（已包含在密码强度中）
      // 可以添加其他因素，如：两步验证、登录记录等
      score += 20

      return Math.min(Math.round(score), maxScore)
    },
    securityLevelText() {
      const score = this.securityScore
      if (score >= 80) return '非常安全'
      if (score >= 60) return '安全'
      if (score >= 40) return '良好'
      if (score >= 20) return '一般'
      return '较弱'
    },
    securityLevelClass() {
      const score = this.securityScore
      if (score >= 80) return 'text-green-600'
      if (score >= 60) return 'text-blue-600'
      if (score >= 40) return 'text-yellow-600'
      if (score >= 20) return 'text-orange-600'
      return 'text-red-600'
    },
    securityProgressBarClass() {
      const score = this.securityScore
      if (score >= 80) return 'bg-green-600'
      if (score >= 60) return 'bg-blue-600'
      if (score >= 40) return 'bg-yellow-600'
      if (score >= 20) return 'bg-orange-600'
      return 'bg-red-600'
    },
    securityLevelDescription() {
      const score = this.securityScore
      const items = []
      
      // 检查需要完善的安全措施
      if (!this.hasPassword) {
        items.push('设置登录密码')
      } else if (this.currentPasswordStrength < 3) {
        items.push('提升密码强度')
      }
      
      if (!this.isPhoneVerified) {
        items.push('验证手机号')
      }
      
      if (!this.isEmailVerified) {
        if (this.userEmail) {
          items.push('验证邮箱')
        } else {
          items.push('绑定并验证邮箱')
        }
      }
      
      if (items.length > 0) {
        return `建议完善：当前安全度 ${score}%`
      }
      
      if (score >= 80) {
        return `您已完成 ${score}% 的安全设置，账户安全性非常高`
      } else if (score >= 60) {
        return `您已完成 ${score}% 的安全设置，账户安全性良好`
      } else if (score >= 40) {
        return `您已完成 ${score}% 的安全设置，建议提升密码强度以增强账户安全性`
      } else {
        return `您已完成 ${score}% 的安全设置，建议完善安全措施以保护账户`
      }
    },
    passwordStrengthText() {
      const level = this.passwordStrength.level
      const map = {
        'weak': '弱',
        'fair': '一般',
        'good': '良好',
        'strong': '强',
        'very-strong': '非常强'
      }
      return map[level] || '弱'
    },
    passwordStrengthClass() {
      const level = this.passwordStrength.level
      const map = {
        'weak': 'text-red-600',
        'fair': 'text-orange-600',
        'good': 'text-yellow-600',
        'strong': 'text-blue-600',
        'very-strong': 'text-green-600'
      }
      return map[level] || 'text-gray-600'
    },
    passwordStrengthBarClass() {
      const level = this.passwordStrength.level
      const map = {
        'weak': 'bg-red-500',
        'fair': 'bg-orange-500',
        'good': 'bg-yellow-500',
        'strong': 'bg-blue-500',
        'very-strong': 'bg-green-500'
      }
      return map[level] || 'bg-gray-300'
    },
    emailButtonText() {
      if (this.userEmail && this.isEmailVerified) return '更换邮箱'
      return this.userEmail ? '绑定并验证邮箱' : '绑定邮箱'
    },
    canSubmitPasswordForm() {
      return this.passwordForm.smsCode &&
             this.passwordForm.newPassword &&
             this.passwordForm.confirmPassword &&
             this.passwordForm.newPassword.length >= 6 &&
             this.passwordForm.newPassword === this.passwordForm.confirmPassword
    },
    isValidEmail() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      return this.emailForm.email && emailRegex.test(this.emailForm.email)
    },
    maskedEmail() {
      if (!this.userEmail) return ''
      const [name, domain] = this.userEmail.split('@')
      if (name.length <= 2) return this.userEmail
      return name.substring(0, 2) + '****@' + domain
    },
    maskedPhone() {
      if (!this.userPhone) return '未设置'
      // 显示格式：前3位 + **** + 后4位，例如：138****5678
      if (this.userPhone.length === 11) {
        return this.userPhone.substring(0, 3) + '****' + this.userPhone.substring(7)
      }
      return this.userPhone
    }
  },
  methods: {
    // 检测密码强度
    checkPasswordStrength(password) {
      if (!password) {
        return { score: 0, level: 'weak', tips: [] }
      }

      let score = 0
      const tips = []

      // 长度检测 (0-2分)
      if (password.length >= 12) {
        score += 2
        tips.push({ text: '长度≥12位', passed: true })
      } else if (password.length >= 8) {
        score += 1
        tips.push({ text: '长度≥8位', passed: true })
      } else if (password.length >= 6) {
        tips.push({ text: '长度≥8位（建议）', passed: false })
      } else {
        tips.push({ text: '长度至少6位', passed: false })
      }

      // 包含小写字母 (0-1分)
      if (/[a-z]/.test(password)) {
        score += 1
        tips.push({ text: '包含小写字母', passed: true })
      } else {
        tips.push({ text: '包含小写字母（建议）', passed: false })
      }

      // 包含大写字母 (0-1分)
      if (/[A-Z]/.test(password)) {
        score += 1
        tips.push({ text: '包含大写字母', passed: true })
      } else {
        tips.push({ text: '包含大写字母（建议）', passed: false })
      }

      // 包含数字 (0-1分)
      if (/\d/.test(password)) {
        score += 1
        tips.push({ text: '包含数字', passed: true })
      } else {
        tips.push({ text: '包含数字（建议）', passed: false })
      }

      // 包含特殊字符 (0-1分)
      if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) {
        score += 1
        tips.push({ text: '包含特殊字符', passed: true })
      } else {
        tips.push({ text: '包含特殊字符（建议）', passed: false })
      }

      // 确定强度等级
      let level = 'weak'
      if (score <= 1) {
        level = 'weak'
      } else if (score === 2) {
        level = 'fair'
      } else if (score === 3) {
        level = 'good'
      } else if (score === 4) {
        level = 'strong'
      } else if (score >= 5) {
        level = 'very-strong'
      }

      return { score, level, tips }
    },
    // 更新密码强度
    updatePasswordStrength() {
      this.passwordStrength = this.checkPasswordStrength(this.passwordForm.newPassword)
    },
    async handleChangePassword() {
      if (!this.canSubmitPasswordForm) {
        ElMessage.warning('请完善验证码和新密码信息')
        return
      }

      if (this.passwordForm.newPassword.length < 6) {
        ElMessage.warning('新密码长度至少6位')
        return
      }

      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        ElMessage.warning('两次输入的密码不一致')
        return
      }

      if (!this.userPhone) {
        ElMessage.error('未获取到手机号，无法通过短信验证码重置密码')
        return
      }

      this.isChangingPassword = true

      try {
        const response = await fetch('/api/auth/reset-password-with-sms', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            phone: this.userPhone,
            smsCode: this.passwordForm.smsCode,
            newPassword: this.passwordForm.newPassword
          })
        })

        const result = await response.json()

        if (result.success) {
          ElMessage.success('密码重置成功')
          this.hasPassword = true
          this.currentPasswordStrength = this.passwordStrength.score

          await this.loadUserInfo()

          this.cancelPasswordForm()

          const newScore = this.securityScore
          if (newScore >= 80) {
            ElMessage.success(`密码重置成功！您的账户安全等级已提升至"非常安全"（${newScore}%）`)
          } else if (newScore >= 60) {
            ElMessage.success(`密码重置成功！您的账户安全等级已提升至"安全"（${newScore}%）`)
          }
        } else {
          ElMessage.error(result.message || '密码重置失败')
        }
      } catch (error) {
        console.error('通过短信验证码重置密码错误:', error)
        ElMessage.error('网络错误，请稍后再试')
      } finally {
        this.isChangingPassword = false
      }
    },
    cancelPasswordForm() {
      this.showPasswordForm = false
      this.passwordForm = {
        smsCode: '',
        newPassword: '',
        confirmPassword: ''
      }
      // 重置密码强度显示
      this.passwordStrength = {
        score: 0,
        level: 'weak',
        tips: []
      }
    },
    async sendSmsCode() {
      if (!this.userPhone) {
        ElMessage.error('未获取到手机号，无法发送验证码')
        return
      }

      if (this.smsCountdown > 0) return

      try {
        const response = await fetch('/api/auth/send-sms', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ phone: this.userPhone })
        })

        const result = await response.json()

        if (result.success) {
          ElMessage.success('验证码已发送，请注意查收（开发环境可查看后端日志或接口返回的调试信息）')
          this.smsCountdown = 60
          if (this.smsTimer) {
            clearInterval(this.smsTimer)
          }
          this.smsTimer = setInterval(() => {
            this.smsCountdown--
            if (this.smsCountdown <= 0) {
              clearInterval(this.smsTimer)
              this.smsTimer = null
            }
          }, 1000)
        } else {
          ElMessage.error(result.message || '发送验证码失败')
        }
      } catch (e) {
        console.error('发送短信验证码错误:', e)
        ElMessage.error('网络错误，请稍后再试')
      }
    },
    async sendEmailVerification() {
      if (!this.isValidEmail) {
        ElMessage.warning('请输入正确的邮箱地址')
        return
      }

      this.isSendingEmail = true

      try {
        const userId = localStorage.getItem('userId')
        if (!userId) {
          ElMessage.error('请先登录')
          this.$router.push('/login')
          return
        }

        const response = await fetch('/api/auth/send-email-verification', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            userId: userId,
            email: this.emailForm.email
          })
        })

        const result = await response.json()

        if (result.success) {
          ElMessage.success('验证码已发送（开发环境请查看后端日志）')
          this.emailForm.emailSent = true
          this.emailCountdown = 60
          this.emailTimer = setInterval(() => {
            this.emailCountdown--
            if (this.emailCountdown <= 0) {
              clearInterval(this.emailTimer)
            }
          }, 1000)
        } else {
          ElMessage.error(result.message || '发送验证码失败')
        }
      } catch (error) {
        console.error('发送邮箱验证码错误:', error)
        ElMessage.error('网络错误，请稍后再试')
      } finally {
        this.isSendingEmail = false
      }
    },
    async verifyEmail() {
      if (!this.emailForm.verificationCode) {
        ElMessage.warning('请输入验证码')
        return
      }

      this.isVerifyingEmail = true

      try {
        const userId = localStorage.getItem('userId')
        if (!userId) {
          ElMessage.error('请先登录')
          this.$router.push('/login')
          return
        }

        const response = await fetch('/api/auth/verify-email', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            userId: userId,
            email: this.emailForm.email,
            verificationCode: this.emailForm.verificationCode
          })
        })

        const result = await response.json()

        if (result.success) {
          ElMessage.success('邮箱验证成功')
          this.userEmail = this.emailForm.email
          this.isEmailVerified = true
          this.cancelEmailForm()
          await this.loadUserInfo()
        } else {
          ElMessage.error(result.message || '验证失败')
        }
      } catch (error) {
        console.error('验证邮箱错误:', error)
        ElMessage.error('网络错误，请稍后再试')
      } finally {
        this.isVerifyingEmail = false
      }
    },
    async resendEmailCode() {
      if (this.emailCountdown > 0) return
      await this.sendEmailVerification()
    },
    cancelEmailForm() {
      this.showEmailForm = false
      this.emailForm = {
        email: '',
        verificationCode: '',
        emailSent: false
      }
      if (this.emailTimer) {
        clearInterval(this.emailTimer)
        this.emailTimer = null
      }
      this.emailCountdown = 0
    },
    openEmailForm() {
      // 打开邮箱表单用于首次绑定或更换邮箱
      this.showEmailForm = true
      this.emailForm = {
        email: '',
        verificationCode: '',
        emailSent: false
      }
      if (this.emailTimer) {
        clearInterval(this.emailTimer)
        this.emailTimer = null
      }
      this.emailCountdown = 0
    },
    async loadUserInfo() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        const response = await fetch(`/api/users/profile/${userId}`)
        const result = await response.json()
        if (result.success && result.data) {
          const data = result.data
          const u = data.user || {}

          this.userEmail = u.email || ''
          this.isEmailVerified = u.email_verified === 1 || u.email_verified === true

          // 获取用户手机号（登录时使用的手机号）
          this.userPhone = u.phone || localStorage.getItem('userPhone') || ''

          // 检查手机验证状态（目前后端未提供，默认视为已验证）
          this.isPhoneVerified = true

          // 检查用户是否已设置密码
          // 前端无法直接知道是否有密码哈希，这里沿用原来的 hasPassword 逻辑
          this.hasPassword = !!this.userPhone

          if (this.hasPassword) {
            this.currentPasswordStrength = this.passwordStrength.score || 3
          }
        }
      } catch (e) {
        console.error('加载用户信息失败:', e)
      }
    },
    async loadLoginHistory() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        const response = await fetch(`/api/users/${userId}/login-history?limit=10`)
        const result = await response.json()
        if (result.success && result.data) {
          this.loginHistory = result.data
        }
      } catch (e) {
        console.error('加载登录记录失败:', e)
      }
    },
    formatTime(timeStr) {
      if (!timeStr) return ''
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
          const minutes = Math.floor(diff / (1000 * 60))
          return minutes <= 1 ? '刚刚' : `${minutes}分钟前`
        }
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天 ' + time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return time.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }) + ' ' + 
               time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      }
    }
  },
  mounted() {
    this.loadUserInfo()
    this.loadLoginHistory()
  },
  beforeUnmount() {
    if (this.emailTimer) {
      clearInterval(this.emailTimer)
    }
  }
}
</script>


